<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Network\NetworkQuery;
use App\Http\Requests\Admin\Network\StationUpdate;
use App\Http\Requests\Admin\Network\ShowRequest;
use App\Http\Requests\Admin\Network\QueryResource;
use App\Http\Requests\Admin\Network\NetworkCreate;
use App\Http\Requests\Admin\Network\NetworkUpdate;
use App\Http\Requests\Admin\Network\NetworkDestroy;
use App\Models\Network;
use App\Models\NetworkAdmin;
use App\Models\NetworkExpress;
use App\Repositories\NetworkRepository;
use App\Repositories\UserLogRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class NetworkController extends Controller
{
    //默认密码
    const BASE_PASSWORD = '123456';
    const NETWORK_STATUS = [
        0 => '申请开通',
        1 => '运营中',
        2 => '已停业',
    ];
    protected $networkRepository;
    protected $userLogRepository;

    /**
     * NetworksController constructor.
     * @param NetworkRepository $networkRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        NetworkRepository $networkRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->networkRepository = $networkRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取网点列表资源列表
     *
     * Date: 2018/05/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function index(QueryResource $request)
    {
        $limit = $request->get('paginate', 15);
        $service_name = $request->get('service_name', false);
        $status = $request->get('status', false);
        if ($service_name === null) {
            $service_name = false;
        }
        if ($status === null) {
            $status = false;
        }
        //0:申请开通  1:运营中  2：已停业
        if ($status !== false && !array_key_exists($status, self::NETWORK_STATUS)) {
            throw new GeneralException('请选择正确网点的状态', 422);
        }
        $networks = $this->networkRepository->getAllNetworks($limit, $service_name, $status);
        return success($networks);
    }

    /**
     * 获取网点详情
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(ShowRequest $request, Network $network)
    {
        $networks = $this->networkRepository->getNetworkDetails($network->id);
        return success($networks);
    }


    /**
     * 创建网点
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param NetworkCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(NetworkCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $attributes['status'] = 1;//共派后台创建默认直接开通
        DB::beginTransaction();
        try {
            unset($attributes['password']);
            $networks = $this->networkRepository->create($attributes);
            //创建网点管理员账户
            $adminUser = new NetworkAdmin();
            $adminUser->name = $request->name;
            $adminUser->phone = $request->phone;
            $adminUser->password = $request->password;
            $adminUser->network_id = $networks->id;
            $adminUser->save();
            //添加所有权限  TODO
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = 0;
        $name = $admin->name;
        $operation = '创建了[' . $networks->designation . ']网点';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return stored($networks);
    }

    /**
     * 更新网点资源
     *
     * Date: 2018/05/11
     * @author Tenny
     * @param NetworkUpdate $request
     * @param network $network
     * @return \Illuminate\Http\JsonResponse
     * @throws  GeneralException
     */
    public function update(NetworkUpdate $request, Network $network)
    {
        $networksAttr = $request->only([
            'designation',
            'name',
            'phone',
            'password',
            'province_id',
            'city_id',
            'district_id',
            'express_id',
            'address',
            'status',
        ]);
        $networkAdmins = array();
        DB::beginTransaction();
        try {
            if ($request->password) {
                $networkAdmins['password'] = $request->password;
            }
            if ($request->phone && $request->phone !== $network->phone) {
                $networkAdmins['phone'] = $request->phone;
            }
            if ($request->name && $request->name !== $network->name) {
                $networkAdmins['name'] = $request->name;
            }
            if (count($networkAdmins) > 0) {
                NetworkAdmin::where('network_id', '=', $network->id)
                    ->where('phone', '=', $network->phone)
                    ->update($networkAdmins);
            }
            unset($networksAttr['password']);
            if (count($networksAttr) > 0) {
                $network->update($networksAttr);
            }
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = 0;
        $name = $admin->name;
        $operation = '更新了[' . $network->designation . ']网点';
        $history = json_encode($network->toArray(), true);
        $actuality = json_encode($networksAttr, true);
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        $result = Network::where('id', '=', $network->id)
            ->withCount(["services"])
            ->with('express')
            ->first();
        return updated($result);
    }

    /**
     * 删除 网点 资源
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param NetworkDestroy $request
     * @param Network $network
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(NetworkDestroy $request, Network $network)
    {
        DB::beginTransaction();
        try {
            $network->services()->detach();
            $network->admins()->delete();
            $network->delete();
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = 0;
        $name = $admin->name;
        $operation = '删除了[' . $network->designation . ']网点';
        $history = null;
        $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }

    /**
     * 检测手机号码是否存在
     *
     * Date: 2018/06/10
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function existence(Request $request)
    {
        $this->validate($request, [
            'phone' => ['required', 'regex:/^(1[3456789])\d{9}$/', 'unique:network_admin,phone']
        ], [
            'phone.required' => '请输入手机号码',
            'phone.regex' => '您输入的手机号码有误',
            'phone.unique' => '您输入的手机号码已存在'
        ]);
        return message('可以注册');
    }

    /**
     * 获取关联站点
     *
     * Date: 2018/06/12
     * @author Tenny
     * @param NetworkQuery $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function relationStation(NetworkQuery $request)
    {
        $limit = $request->get('paginate', 15);
        $network_id = $request->get('network_id', 15);
        $networks = $this->networkRepository->getRelationStations($network_id, $limit);
        return success($networks);
    }

    /**
     * 修改网点关联站点
     *
     * Date: 2018/06/12
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws  GeneralException
     */
    public function updateNetworkStation(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer'
        ], [
            'id.required' => '请上传id',
            'id.integer' => '请上传正确的id',
        ]);
        $relation_id = $request->get('id', false);
        $networkStations = array_filter($request->only([
            'credit',
            'unit_price',
        ]), function ($value) {
            if ($value === null || $value === '') {
                return false;
            } else {
                return true;
            }
        });
        $networkStation = NetworkExpress::where('id', '=', $relation_id)->with(['services', 'network'])->first();
        $networkArr = [];
        if ($networkStation->credit && array_key_exists('credit', $networkStations)) {
            if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $networkStations['credit'])) {
                return failed('请上传正确的信用', 422);
            }
            if ($networkStations['credit'] !== $networkStation->credit) {
                $networkArr['credit'] = $networkStation->credit;
            }
        }
        if ($networkStation->unit_price && array_key_exists('unit_price', $networkStations)) {
            if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $networkStations['unit_price'])) {
                return failed('请上传正确的单价', 422);
            }
            if ($networkStations['unit_price'] !== $networkStation->unit_price) {
                $networkArr['unit_price'] = $networkStation->unit_price;
            }
        }
        if (count($networkArr) > 0) {
            $networkStation->update($networkStations);
            //记录日志
            $admin = Auth::guard('admin')->user();
            $uid = $admin->id;
            $service_id = 0;
            $name = $admin->name;
            $operation = '更新了关联网点[' . $networkStation->id . ']关系';
            $history = json_encode($networkArr, true);
            $actuality = json_encode($networkStations, true);
            $order_id = 0;//非订单
            $ip = $request->getClientIp();
            $type = 2;//共派管理员
            $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        }
        return success($networkStation);
    }

    /**
     * 解除关联网点
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroyRelation(Request $request)
    {
        $relation_id = $request->get('id', false);
        $networkExpress = NetworkExpress::where('id', '=', $relation_id)->with(['services', 'network'])->first();
        $networkExpress->delete();
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = 0;
        $name = $admin->name;
        $operation = '解除除了[' . $networkExpress->services->designation . ']与网点[' . $networkExpress->network->designation . ']的关联';
        $history = null;
        $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }

    /**
     * 重置网点密码
     *
     * Date: 2018/06/013
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function password(Request $request)
    {
        $params = $this->validate($request, [
            'network_id' => 'required',
        ], [
            'network_id.required' => '请上传网点id',
        ]);
        $network = Network::where('id', '=', $params['network_id'])->first();
        if ($network->phone) {
            $networkAdmin = NetworkAdmin::where('network_id', '=', $params['network_id'])
                ->where('phone', '=', $network->phone)
                ->first();
            $networkAdmin->password = self::BASE_PASSWORD;
            $networkAdmin->save();
        } else {
            return failed('找不到该网点', 400);
        }
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = 0;
        $name = $admin->name;
        $operation = '重置了网点[' . $network->designation . ']的密码';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return updated([], '该网点的密码重置成功');
    }
}
